package com.hyt.it.ogt.ks.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.hyt.it.ogt.ks.job.TaskJob;
import com.hyt.it.ogt.ks.service.es.IEsAndDbService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.mapper.CandidatePaperMapper;
import com.hyt.it.ogt.ks.model.entity.CandidatePaper;
import com.hyt.it.ogt.ks.model.entity.CandidateProcess;
import com.hyt.it.ogt.ks.model.vo.paper.PItemDTO;
import com.hyt.it.ogt.ks.service.ICandidateProcessService;
import com.hyt.it.ogt.ks.service.IExamCacheService;
import com.hyt.it.ogt.ks.service.IPaperService;
import com.hyt.it.ogt.ks.util.KeyDefineCommon;
import com.hyt.it.ogt.ks.util.StringUtil;
import com.hyt.it.ogt.ks.websocket.CandidateWebSocketService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试类
 *
 * @author 刘恒活
 * @since 2020/8/24 10:12
 */
@RestController
@RequestMapping("/ks/test/")
@Api(tags = "9.测试用接口", value = "测试用接口")
@ApiSort(9)
@Slf4j
public class TestController {
    @Resource
    private CandidatePaperMapper candidatePaperMapper;
    @Resource
    private ICandidateProcessService iCandidateProcessService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IPaperService iPaperService;
    @Resource
    private IExamCacheService iExamCacheService;
    @Resource
    private KwClient kwClient;
    @Resource
    private CandidateWebSocketService candidateWebSocketService;

    @Resource
    private TaskJob taskJob;

    @Resource
    private IEsAndDbService esAndDbService;

    @GetMapping("zmTest")
    public void zmTest(String param) {
        taskJob.updateLogOther(param);
    }

    @GetMapping("deleteRedisCache")
    public void deleteRedisCache(String key) {
        redisTemplate.delete(key);
    }

    @GetMapping("deleteRedisCacheByLike")
    public void deleteRedisCacheByLike(String key) {
        Set<String> keys = redisTemplate.keys(key);
        if (CollectionUtils.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    @GetMapping("deleteCandidateAndPaper")
    public void deleteCandidate() {
        List<CandidateProcess> list = iCandidateProcessService.list();
        list.stream().forEach(item -> {
            String key = KeyDefineCommon.getCandidateCacheCandidatePaperInfo(item.getCandidateId());
            if (!redisTemplate.delete(key)) {
                log.info("删除缓存{}失败", key);
            }
        });

        List<CandidatePaper> list1 = candidatePaperMapper.selectList(null);
        list1.stream().forEach(item -> {
            String key = KeyDefineCommon.getPaperInfoKey(item.getPaperId(), item.getPaperVersion());
            if (!redisTemplate.delete(key)) {
                log.info("删除缓存{}失败", key);
            }
        });
    }

    @GetMapping("updateOldData")
    public void updateOldData() {
        LambdaQueryWrapper<CandidateProcess> query = Wrappers.lambdaQuery();
        query.isNull(CandidateProcess::getPasswordNumber);
        List<CandidateProcess> list = iCandidateProcessService.list(query);
        list.stream().forEach(item -> {
            CandidateProcess entity = new CandidateProcess();
            entity.setId(item.getId());
            entity.setPasswordNumber(StringUtil.encrypt(item.getAdmissionNumber()));
            iCandidateProcessService.updateById(entity);
        });
    }

    @GetMapping("testProcess")
    public void testProcess(String candidateID) {
        LambdaQueryWrapper<CandidateProcess> query = Wrappers.lambdaQuery();
        query.eq(CandidateProcess::getCandidateId, candidateID);
        CandidateProcess entity = new CandidateProcess();
        entity.setUpdateDate(LocalDateTime.now());
        iCandidateProcessService.update(entity, query);
    }

    @GetMapping("setCache")
    public void setCache(String key, String value) {
        Map<String, PItemDTO> itemMap = new HashMap<>();
        itemMap.put("111", PItemDTO.builder().itemId("222").build());
        itemMap.put("aaa", PItemDTO.builder().itemId("bbb").build());
        redisTemplate.opsForHash().putAll(key, itemMap);
        redisTemplate.expire(key, 10, TimeUnit.SECONDS);

        //redisTemplate.opsForValue().set(key, value);
    }

    @GetMapping("getCache")
    public Object getCache(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @GetMapping("getPaperItemByTopicId")
    public Object getPaperItemByTopicId(String paperId, String paperVersion, String topicId) {
        return iPaperService.getPaperItemByTopicId(paperId, paperVersion, topicId);
    }

    @GetMapping("getPItem")
    public Object getPItem(String paperId, String paperVersion, String itemId) {
        return iPaperService.getPItem(paperId, paperVersion, itemId);
    }

    @GetMapping("testMQ")
    public void testMQ() {
        //candidateAnswerLogProducer.sendMessage(CandidateAnswerLogBackupDTO.builder().build());
    }

    @GetMapping("loadTranslateContent")
    public void loadTranslateContent(String examId, String language) {
        ApiResponse<Map<String, String>> ret = kwClient.getAllExamPaper(examId);
        ret.getData().forEach((k, v) -> {
            iExamCacheService.putTranslateToCache(k, v, language);
        });
    }

    @ApiOperation(value = "9.1.12 手动清理试卷翻译的ehcache缓存", response = Integer.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "language", value = "语言代码", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(12)
    @GetMapping("clearTranslateEncache")
    public void clearTranslateEncache(String examId, String language) {
        ApiResponse<Map<String, String>> ret = kwClient.getAllExamPaper(examId);
        ret.getData().forEach((k, v) -> {
            iExamCacheService.clearPaperTransalteEncache(k, v, language);
        });
        log.info("手动清理试卷翻译的ehcache缓存成功");
    }

    @ApiOperation(value = "9.1.13 手动清理试信息的ehcache缓存", response = Integer.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pwd", value = "清理密码 ks_dict id=12", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(13)
    @GetMapping("clearPaperInfoEncahce")
    public Boolean clearPaperInfoEncahce(@RequestParam(required = true) String pwd) {
        Boolean isSucess = iExamCacheService.clearPaperInfoEncache(pwd);
        if (Objects.equals(Boolean.TRUE, isSucess)) {
            log.info("手动清理试信息的ehcache缓存成功");
        }
        return isSucess;
    }

    @ApiOperation(value = "9.1.14 手动清理机构皮肤和名称Redis缓存", response = Integer.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pwd", value = "清理密码 ks_dict id=12", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "examId", value = "要清理缓存的考试id", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(14)
    @GetMapping("clearProjectSkin")
    public Boolean clearProjectSkin(@RequestParam(required = true) String pwd, @RequestParam(required = true) String examId) {
        Boolean isSucess = iExamCacheService.clearProjectSkinRedisCache(pwd, examId);
        if (Objects.equals(Boolean.TRUE, isSucess)) {
            log.info("手动清理试信息的ehcache缓存成功");
        }
        return isSucess;
    }

    @GetMapping("test01")
    public int test01() {
        log.info("-----------test01--onlineSession  size--------{}", candidateWebSocketService.getOnlineSession().size());

        candidateWebSocketService.getOnlineSession().forEach((k,v) -> {
            log.info("-----------test01-----onlineSession------{},{}", k, v.getId());
            try {
                v.getBasicRemote().sendText("hi,bug");
            } catch (IOException e) {
                log.error("", e);
            }
        });
        return 1;
    }
}
